<?php
/**
 * App to manage companies
 *
 * @category Abovo
 *
 * @package Abovo_App_Crm
 * 
 * @subpackage Abovo_App_Crm_Companies
 *
 * @author Antti Holvikari <anttih@gmail.com>
 * 
 * @license http://opensource.org/licenses/gpl-license.php GPL
 */

/**
 * App to manage companies
 * 
 * Part of the CRM module
 *
 * @category Abovo
 * 
 * @package Abovo_App_Crm
 * 
 * @subpackage Abovo_App_Crm_Companies
 */
class Abovo_App_Crm_Companies extends Abovo_App_Crm {
    
    /**
     * Default action
     *
     * @var string
     */
    protected $_action_default = 'search';
    
    /**
     * Model for companies
     *
     * @var Abovo_Model_Company
     */
    private $_companies;
    
    /**
     * One company
     *
     * @var Solar_Sql_Row
     */
    public $company;
    
    /**
     * Company form
     *
     * @var Solar_Form
     */
    public $company_form;
    
    /**
     * List of companies
     *
     * @var Solar_Sql_Rowset
     */
    public $companies;
    
    /**
     * Tags and their counts
     *
     * @var array
     */
    public $tags;
    
    /**
     * Citys
     *
     * @var array
     */
    public $citys;
    
    /**
     * Contacts
     *
     * @var Solar_Sql_Rowset
     */
    public $contacts;
    
    /**
     * Search form element hints
     *
     * @var array
     */
    public $sform_elements = array();
    
    /**
     * Set up models
     *
     * @return void
     */
    public function _setup()
    {
        parent::_setup();
        $this->_companies = Solar::factory('Abovo_Model_Company_Lead');
    }
    
    /**
     * Search companies
     *
     * @return void
     */
    public function actionSearch()
    {
        // instantiate form object and use GET
        $form = Solar::factory(
            'Abovo_Form',
            array('attribs' => array('method' => 'get'))
        );
        
        // Form elements. Types are handeled by the view
        // so they're not here
        $elements = array(
            'keywords' => array(
                'attribs' => array(
                    'size' => 30,
                ),
            ),
            'key' => array(
                'value' => null,
                'options' => null,
            ),
            'process' => array(
                'value' => $this->locale('PROCESS_SEARCH'),
            )
        );
        
        // set form elements
        $form->setElements($elements);
        
        // populate and get submitted values (if any)
        $form->populate();
        $values = $form->values();
        
        // is there a request?
        if (! empty($values['key'])
        && ! empty($values['keywords'])) {
            
            // set search key and search keywords
            $keys = array();
            $keys[$values['key']] = $values['keywords'];
            
            // perform search
            $this->companies = $this->_companies->find($keys);
        }
        
        // fetch tags if no companies found
        if (count($this->companies) === 0) {
            $this->tags  = $this->_companies->tags->fetchAllCounts();
            $this->citys = $this->_companies->fetchCitys();
        }
        
        // take the elements only and assign for view
        $this->sform_elements = $form->elements;
    }
    
    /**
     * Show one company
     *
     * @return void
     */
    public function actionShow($id = null)
    {
        $info = $this->_companies->fetch((int) $id);

        if (count($info) === 0) {
            $this->errors[] = $this->locale('ERR_COMPANY_NOT_FOUND');
            $this->_action = 'error';
            $this->_view = 'error';
            return;
        }
        
        $this->company = $info;
        
        $this->contacts = $info->fetchContacts();
        
        // add company to location stack
        $this->_addBreadCrumb($this->company->name);
        
        // flash notification for company save
        $this->_msgSuccess($this->_session->getFlash('saved'));

        // flash notification for company add
        $this->_msgSuccess($this->_session->getFlash('added'));
    }
    
    /**
     * Edit company
     *
     * @return void
     */
    public function actionEdit($id = null)
    {
        // we need it to be integer
        settype($id, 'int');
        
        // fetch company info
        $info = $this->_companies->fetch($id)->toArray();
        
        // if company not found, redirect to search page
        if (empty($info)) {
            $this->_redirect('crm/companies/search');
        }
        
        // add item to location
        $this->_addBreadCrumb($info['name'], "crm/companies/show/$id");
        
        // ------------------------------------
        //
        // delete
        //
        
        if ($this->_isProcess('delete')) {
            $this->_companies->delete(array('id = ?' => $id));
            $this->_session->setFlash('deleted', $this->locale('TEXT_COMPANY_DELETED'));
            return $this->_forward('search');
        }
        
        // -------------------------------------
        //
        // edit
        //
        
        $form = $this->_companies->form();
        
        // save?
        if ($this->_isProcess('save')) {
            if ($form->validate()) {
                // get submitted values
                $values = $form->values();
                
                // set company id
                $values['company']['id'] = $id;
                
                // set user handle
                $values['company']['handle'] = Solar::registry('user')->auth->handle;
                
                // save
                $info = $this->_companies->save($values['company']);
                
                // use only the first feedback message
                $this->_session->setFlash('saved', $form->feedback[0]);
                
                // forward to actionShow() action
                return $this->_redirect('crm/companies/show/' . $id);
            }
        } else {
            // set tags as string
            $info['tags'] = implode(' ', $info['tags']);
            
            // populate form from model object
            $form->populate(array('company' => $info));
        }
        
        // assign for view
        $this->company_form = $form;
    }
    
    /**
     * 
     * Adds one company
     * 
     * @return void
     * 
     */
    public function actionAdd()
    {
        // get form
        $form = $this->_companies->form();
        
        if ($this->_isProcess('save') && $form->validate()) {
            // get submitted values
            $values = $form->values();
            
            // user handle
            $values['company']['handle'] = Solar::registry('user')->auth->handle;
            
            // save
            $info = $this->_companies->save($values['company']);
            
            // add flash
            $this->_session->setFlash('added', $this->locale('TEXT_COMPANY_ADDED'));
            
            // forward to company info page
            return $this->_redirect('crm/companies/show/' . $info['id']);
        }
        
        // assign form for view
        $this->company_form = $form;
    }
    
    /**
     * undocumented function
     *
     * @return void
     **/
    public function actionAjaxCompanies($name = '')
    {
        if (! $this->_request->isXhr()) {
            return $this->_forward('search');
        }
        
        $this->companies = array();
        
        if((string) $name != '') {
            $this->companies = $this->_companies->find(array('name' => $name), 5)->toArray();
        }
        
        // disable layout, this is an AJAX request
        $this->_layout = false;
    }
}
